package com.xbongbong.pro.statistic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.message.domain.entity.PushEntity;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.dto.DwDelLogDTO;
import com.xbongbong.paas.pojo.vo.DwDelLogVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.NamedThreadFactory;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.pro.datawarning.pojo.dto.DataWarningMessageAddDTO;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.domain.entity.DataWarningEntity;
import com.xbongbong.pro.domain.entity.DataWarningHistoryEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.datacenter.datawarning.enums.ActionTypeEnum;
import com.xbongbong.pro.enums.datacenter.datawarning.enums.DataWarningConditionEnum;
import com.xbongbong.pro.enums.datacenter.datawarning.enums.DataWarningStrategyTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.service.toolbox.statistic.help.ChartDtoHelp;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.model.DataWarningHistoryModel;
import com.xbongbong.pro.statistic.model.DataWarningModel;
import com.xbongbong.pro.statistic.pojo.ChildValuePojo;
import com.xbongbong.pro.statistic.pojo.DwExecutorPojo;
import com.xbongbong.pro.statistic.pojo.DwFilterChartPojo;
import com.xbongbong.pro.statistic.pojo.DwHistoryDataPojo;
import com.xbongbong.pro.statistic.pojo.DwTriggerConditionPojo;
import com.xbongbong.pro.statistic.pojo.dto.HandleSingleChartDTO;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import com.xbongbong.pro.statistic.result.pojo.dto.ChartResultDTO;
import com.xbongbong.pro.statistic.result.pojo.dto.DiyResultDTO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultChartVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultDataChartVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultTableVO;
import com.xbongbong.pro.statistic.service.ChartResultService;
import com.xbongbong.pro.statistic.service.DataWarningService;
import com.xbongbong.pro.statistic.service.DataWarningStrategyService;
import com.xbongbong.pro.statistic.service.DwExecutorService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.SysEnvHelp;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.xbongbong.pro.statistic.enums.ChartTypeEnum.BAR_CHART;
import static com.xbongbong.pro.statistic.enums.ChartTypeEnum.BIAXIAL_CHART;
import static com.xbongbong.pro.statistic.enums.ChartTypeEnum.DATA_STATISTICS_TABLE;


/**
 * @ClassName DataWarningStrategyServiceImpl
 * @Description 数据预警：策略执行
 * @Author mengna.Deng
 * @Date 2021/4/23 16:57
 * @Version 1.0
 */
@Service("dataWarningStrategyService")
public class DataWarningStrategyServiceImpl implements DataWarningStrategyService {
    private static final Logger LOG = LoggerFactory.getLogger(DataWarningStrategyServiceImpl.class);

    @Resource
    private DataWarningModel dataWarningModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    ChartCustomModel chartCustomModel;
    @Resource
    ChartDtoHelp chartDtoHelp;
    @Resource
    PaasFormExplainModel paasFormExplainModel;
    @Resource
    WorkOrderExplainModel workOrderExplainModel;
    @Resource
    PaasFormModel paasFormModel;
    @Resource
    WorkOrderFormModel workOrderFormModel;
    @Resource
    DataWarningHistoryModel dataWarningHistoryModel;
    @Resource
    DwExecutorService dwExecutorService;
    @Resource
    CompanyConfigModel companyConfigModel;
    @Resource
    PaasRedisHelper paasRedisHelper;
    @Resource
    ChartResultService chartResultService;
    @Resource
    PushModel pushModel;
    @Resource
    private DataWarningService dataWarningService;
    @Resource
    private SysEnvHelp sysEnvHelp;


    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 120L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10), new NamedThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());

    @Override
    public void dataWarningStrategy(BaseDTO baseDTO) {
        LOG.info("enter dataWarningStrategy");
        Integer pageSize = 200;
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("enable", BasicConstant.IS_USE);
        // 获取有启用数据预警的公司
        List<String> corpidList = dataWarningModel.findCorps(param);

        // 该业务接口开始时间
        long dwTriggerTime = DateTimeUtil.getInt();
        // 当前零点
        long zero = DateTimeUtil.getTodayInt();

        // 所有公司的，不用拼接corpid
        String dwTriggerTimeKey = RedisPrefixConstant.DW_TRIGGER_TIME_KEY;
        companyConfigModel.save("0", CompanyConfigEnum.DW_TRIGGER_TIME.getAlias(), CompanyConfigEnum.DW_TRIGGER_TIME.getName(), String.valueOf(dwTriggerTime));
        paasRedisHelper.setValue(RedisConstant.KEY_COMPANY_CONFIG, dwTriggerTimeKey, dwTriggerTime, TimeConstant.SECONDS_TWO_HOUR);

        // 对这些公司分页处理
        param.put("orderByStr", "add_time asc, corpid asc");
        param.put("columns", "corpid,fee_type");
        param.put("corpidIn",corpidList);
        // 过滤无效公司（解绑，套餐过期）,套餐时间,过滤标准版和高级版
        param.put("status",BasicConstant.ONE);
        param.put("feeEndTimeGte", DateUtil.getNow());
        param.put("feeTypeIn",new ArrayList<Integer>(){{add(PackageTypeEnum.ULTIMATE.getType());}});
//        Integer companyCount = companyModel.getEntitysCount(param);

        // 每个公司当天已经执行了多少次预警
        Map<String, Object> dwParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        dwParam.put("del", DelEnum.NORMAL.getDel());
        dwParam.put("enable", BasicConstant.IS_USE);
        dwParam.put("addTimeStart", zero);
        dwParam.put("groupByStr", "corpid");
        dwParam.put("columns","data_warning_id,count(data_warning_id) trigger_num,corpid");

        // 遍历公司
        Integer threadNum = corpidList.size() / pageSize + 1;
        LOG.info("enter dataWarningStrategy2");
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                try {
                    for (int i = 1; i < threadNum + 1; i++) {
                        LOG.info("enter dataWarningStrategy3");
                        Integer start = (i - 1) * pageSize;
                        Integer pageNum = i * pageSize;
                        param.put("start", start);
                        param.put("pageNum", pageNum);
                        // 分页循环
                        List<CompanyEntity> companyList = companyModel.findEntitys(param);
                        if (CollectionUtils.isEmpty(companyList)){
                            break;
                        }
                        LOG.info("enter dataWarningStrategy4");
                        List<String> companyIds = companyList.stream().map(CompanyEntity::getCorpid).collect(Collectors.toList());
                        LOG.info("enter dataWarningStrategy5");
                        // 获取每个公司已经执行的预警次数
                        dwParam.put("corpidIn",companyIds);
                        List<DataWarningHistoryEntity> dataWarningHistoryEntityList = dataWarningHistoryModel.findEntitys(dwParam);
                        Map<String,Integer> corpidExecuteNumberMap = dataWarningHistoryEntityList.stream().collect(Collectors.toMap(DataWarningHistoryEntity::getCorpid, DataWarningHistoryEntity::getTriggerNum));
                        // 以每个公司为单位去执行策略
                        LOG.info("********************数据预警业务start********************");
                        boolean isGrayEnvironmentEnable = sysEnvHelp.isGrayEnvironmentEnable();
                        companyList.forEach(companyEntity ->{

                            // 此公司的预警可执行次数大于0才处理
                            String corpid = companyEntity.getCorpid();

                            if (sysEnvHelp.isGrayEnvironment()) {
                                if (!isGrayEnvironmentEnable) {
                                    return;
                                }
                                if (!sysEnvHelp.checkIsCrayCompany(corpid)) {
                                    return;
                                }
                            } else {
                                if (isGrayEnvironmentEnable) {
                                    if (sysEnvHelp.checkIsCrayCompany(corpid)) {
                                        return;
                                    }
                                }
                            }

                            Integer executeNumber = PaasConstant.ULTIMATE_NUMBER_EXECUTIONS;
                            Integer executedNumber = null != corpidExecuteNumberMap.get(corpid) ? corpidExecuteNumberMap.get(corpid) : 0;
                            executeNumber = executeNumber - executedNumber;
                            LOG.info("********************corpid :" + corpid + "；开始执行数据预警start********************");
                            try {
                                if ( executeNumber > 0){
                                    handleStrategy(corpid,DateTimeUtil.getInt(),executeNumber);
                                }
                            } catch (XbbException e) {
                                LOG.error("********************corpid :" + corpid + "；执行数据预警失败********************",e);
                            }

                            LOG.info("********************corpid :" + corpid + "；执行数据预警end********************");

                        });
                        LOG.info("********************数据预警业务end********************");
                    }
                } catch (Exception e) {
                    LOG.error("数据预警定时任务执行失败",e);
                }
            }
        };
        threadPoolExecutor.execute(runnable);

    }

    @Override
    public DwDelLogVO batchPhysicalDelete(DwDelLogDTO dwDelLogDTO) throws XbbException {
        // 当天的零点，一个月前的零点
        Long lastMonthZero = DateTimeUtil.getLastMonthFromTodayInt();
        Integer pageSize = 200;
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("orderByStr", "add_time asc");
        param.put("columns", "corpid");
        // 过滤无效公司（解绑，套餐过期）,套餐时间,过滤标准版
        param.put("status",BasicConstant.ONE);
        Integer companyCount = companyModel.getEntitysCount(param);
        // 遍历公司
        Integer threadNum = companyCount / pageSize + 1;
        LOG.info("********************数据预警历史批量删除start********************");
        // 测试用
        if (null != dwDelLogDTO.getCorpidList()){
            dataWarningHistoryModel.batchPhysicalDelete(lastMonthZero,dwDelLogDTO.getCorpidList());
            return new DwDelLogVO();
        }
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                try {
                    for (int i = 1; i < threadNum + 1; i++) {
                        Integer start = (i - 1) * pageSize;
                        Integer pageNum = i * pageSize;
                        param.put("start", start);
                        param.put("pageNum", pageNum);
                        // 分页循环
                        List<CompanyEntity> companyList = companyModel.findEntitys(param);
                        List<String> corpidIn;
                        if (companyList.size()>0){
                            corpidIn = companyList.stream().map(CompanyEntity::getCorpid).collect(Collectors.toList());
                            LOG.info("********************corpidIn :" + corpidIn + "；开始执行批量删除start********************");
                            Integer num =dataWarningHistoryModel.batchPhysicalDelete(lastMonthZero,corpidIn);
                            LOG.info("********************" + "成功删除" + num + "条记录" + "*****批量删除end********************");
                        }
                    }
                    LOG.info("********************数据预警历史批量删除end********************");
                } catch (Exception e) {
                    LOG.error(BiErrorCodeEnum.API_ERROR_241006.getMsg());
                }
            }
        };
        threadPoolExecutor.execute(runnable);
        return new DwDelLogVO();
    }

    public void handleStrategy(String corpid,long dwTriggerTime,Integer executeNumber) throws XbbException {
        // 1.查询出此公司的所有有开预警的图表和所有开启的预警设置（目前只支持自定义图表有预警设置）

        // 查出该公司所有的开启的预警设置
        int executeCount = 0;
        Map<String, Object> param = new HashMap<String, Object>(PaasConstant.DEFAULT_INITIAL_CAPACITY){{
            put("del", DelEnum.NORMAL.getDel());
            put("enable", BasicConstant.IS_USE);
            put("corpid", corpid);
        }};
        List<DataWarningEntity> dataWarningEntityList = dataWarningModel.findEntitys(param);

        // Map<Long,List<DataWarningEntity>> key为chartId,value为对应的数据预警设置（为了便于下面每个图表中查询数据预警是否触发）
        Map<Long,List<DataWarningEntity>> chartIdWithDwEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // Map<Long,List<DataWarningEntity>> key为formId,value为对应的数据预警设置（目前还没用到，考虑触发条件的字段名字不是最新的，可能需要再更新下attrName）
        Map<Long,List<DwTriggerConditionPojo>> formIdWithTriggerConditionsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 当前时间的小时
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        Set<Long> countFormIdList = new HashSet<>();
        Set<Long> workOrderCountFormIdList = new HashSet<>();

        Iterator<DataWarningEntity> iterator = dataWarningEntityList.iterator();
        while (iterator.hasNext()){
            DataWarningEntity dataWarningEntity = iterator.next();
            // 过滤当前时间不在采集范围内的预警
            JSONObject samplingRange = dataWarningEntity.getSamplingRange();
            String startTime = samplingRange.getString(StringConstant.START_TIME);
            String endTime = samplingRange.getString(StringConstant.END_TIME);
            startTime = startTime.substring(0, startTime.indexOf(":"));
            endTime = endTime.substring(0, endTime.indexOf(":"));
            if (!(Integer.parseInt(startTime) <= hour && Integer.parseInt(endTime) >= hour)) {
                iterator.remove();
                continue;
            }
            // 获取图表要展示的是计数的formIdList（特殊处理）
            List<DwTriggerConditionPojo> triggerConditionPojoList = dataWarningEntity.getTriggerCondition().toJavaList(DwTriggerConditionPojo.class);
            if (CollectionUtils.isNotEmpty(triggerConditionPojoList)){
                DwTriggerConditionPojo dwTriggerConditionPojo = triggerConditionPojoList.get(0);
                if (Objects.equals(dwTriggerConditionPojo.getAttr(),"count")){
                    if (Objects.equals(dwTriggerConditionPojo.getBusinessType(),XbbRefTypeEnum.WORK_ORDER.getCode())){
                        workOrderCountFormIdList.add(dwTriggerConditionPojo.getFormId());
                    }else {
                        countFormIdList.add(dwTriggerConditionPojo.getFormId());
                    }
                }
            }

            // 获取chartIdWithDwEntityMap和formIdWithTriggerConditionsMap两个map
            Long chartId = dataWarningEntity.getChartId();
            if (chartIdWithDwEntityMap.containsKey(chartId)){
                chartIdWithDwEntityMap.put(chartId,new ArrayList<DataWarningEntity>(){{addAll(chartIdWithDwEntityMap.get(chartId));add(dataWarningEntity);}});
            }else {
                chartIdWithDwEntityMap.put(chartId,new ArrayList<DataWarningEntity>(){{add(dataWarningEntity);}});
            }
            // 目前只有一个触发条件
            List<DwTriggerConditionPojo> triggerConditionList = dataWarningEntity.getTriggerCondition().toJavaList(DwTriggerConditionPojo.class);
            if (CollectionUtils.isNotEmpty(triggerConditionList)){
                DwTriggerConditionPojo pojo = triggerConditionList.get(0);
                if (formIdWithTriggerConditionsMap.containsKey(pojo.getFormId())){
                    formIdWithTriggerConditionsMap.put(chartId,new ArrayList<DwTriggerConditionPojo>(){{addAll(formIdWithTriggerConditionsMap.get(pojo.getFormId()));add(pojo);}});
                }else {
                    formIdWithTriggerConditionsMap.put(chartId,new ArrayList<DwTriggerConditionPojo>(){{add(pojo);}});
                }
            }

        }

        // 查询该公司所有图表ids，一个公司的图表不会特别多，暂时不做分页
        Set<Long> chartIds = dataWarningEntityList.stream().map(DataWarningEntity::getChartId).collect(Collectors.toSet());
        param.clear();
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", corpid);
        param.put("idIn",chartIds);
        param.put("chartTypeIn",ChartTypeEnum.getDwChartType());
        List<ChartEntity> chartEntityList = chartCustomModel.findEntitys(param);

        // 2.过滤图表,（统计图：汇总字段不包含此图表中预警设置的任一一个触发条件则过滤此图表。指标图：指标...。柱形图/折线图：值...。）
        DwFilterChartPojo dwFilterChartPojo = filterChart(corpid,chartEntityList,chartIdWithDwEntityMap,countFormIdList,workOrderCountFormIdList);
        // 获取过滤后的dataWarningEntityList
        dataWarningEntityList = dwFilterChartPojo.getDataWarningEntityList();
        // 根据过滤后的图表查出所有图表中所有的form，以及表单的解释，避免多个图表查询相同的form解释(为了触发条件的字段名字是最新的)
        Map<Long,PaasFormExplainEntity> formIdWithExplainMap = dwFilterChartPojo.getFormIdWithExplainMap();
        Map<Long,String> formIdNameMap = dwFilterChartPojo.getFormIdNameMap();
        // 工单特有
        Map<Long,WorkOrderExplainEntity> workOrderFormIdWithExplainMap = dwFilterChartPojo.getWorkOrderFormIdWithExplainMap();
        Map<Long,String> workOrderFormIdNameMap = dwFilterChartPojo.getWorkOrderFormIdNameMap();
        // 计算字段名称
        Map<Long,Map<String,String>> chartIdWithComputedAttrMap = dwFilterChartPojo.getChartIdWithComputedAttrMap();
        // 3.获取执行人 、消息
        List<DwExecutorPojo> executorList = dwExecutorService.getExecutorList(corpid,dataWarningEntityList);
        Map<Long,List<UserEntity>> executorMap = executorList.stream().collect(Collectors.toMap(DwExecutorPojo::getDataWarningId, DwExecutorPojo::getExecutorList));
        Map<Long,List<String>> executorUserIdMap = executorList.stream().collect(Collectors.toMap(DwExecutorPojo::getDataWarningId, DwExecutorPojo::getExecutorIdList));
        // 要同送的消息List
        List<MessageRabbitMqDTO> mqDTOArrayList = new ArrayList<>();
        // 要插入到预警历史表里的list
        List<DataWarningHistoryEntity> insertHistoryList = new ArrayList<>();
        // 要更新的预警表
        List<DataWarningEntity> updateList = new ArrayList<>();

        // 4.循环图表，在原有的图表查询条件中（图表的分类，系列）。
        for (ChartEntity chartEntity : chartEntityList) {
            // 循环次数判断
            if (executeCount >= executeNumber){
                break;
            }
            executeCount = handleSingleChartEntity(new HandleSingleChartDTO(executeCount,executeNumber,corpid,chartEntity, chartIdWithDwEntityMap, dwTriggerTime, executorMap, formIdWithExplainMap, formIdNameMap, workOrderFormIdWithExplainMap,workOrderFormIdNameMap,chartIdWithComputedAttrMap,insertHistoryList, mqDTOArrayList, executorUserIdMap,updateList,null,null));
        }

        // 5.预警历史记录批量插入
        int count = insertHistoryList.size();
        int start = 0;
        int pageNum = 2000;
        for (; start <= count; start = start + pageNum) {
            // 分组数据的endIndex
            int endIndex = (start + pageNum) <= count ? start + pageNum : count;
            List<DataWarningHistoryEntity> subList = insertHistoryList.subList(start, endIndex);
            if (subList.size()>0){
                dataWarningHistoryModel.insertBatch(subList);
            }
        }

        // 6.数据预警设置表更新触发次数和最近一次触发时间
        count = updateList.size();
        start = 0;
        pageNum = 2000;
        for (; start <= count; start = start + pageNum) {
            // 分组数据的endIndex
            int endIndex = (start + pageNum) <= count ? start + pageNum : count;
            List<DataWarningEntity> subList = updateList.subList(start, endIndex);
            if (subList.size()>0){
                dataWarningModel.updateBatch(subList,corpid);
            }
        }

        // 7.消息分发
        Iterator<MessageRabbitMqDTO> mqIterator = mqDTOArrayList.iterator();
        List<Long> delIdList = new ArrayList<>();
        while (mqIterator.hasNext()){
            MessageRabbitMqDTO mq = mqIterator.next();
            // 数据每两小时同步一次，但消息每个人只能提醒一次
            Map<String, Object> mqParam = new HashMap<String, Object>(PaasConstant.DEFAULT_INITIAL_CAPACITY){{
                put("del", DelEnum.NORMAL.getDel());
                if (CollectionUtils.isNotEmpty(mq.getRefIds())){
                    put("refId",mq.getRefIds().get(0));
                }
                put("corpid", corpid);
                put("refEntity",PushTypeEnum.DATA_WARNING_PUSH.getCode());
                put("pushTime",mq.getPushTime());
            }};
            List<PushEntity> pushEntityList = pushModel.findEntitys(mqParam);
            PushEntity pushEntity;
            List<String> userIdList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(pushEntityList)){
                pushEntity = pushEntityList.get(0);
                // 消息的文案改了要更新
                String msgObject = pushEntity.getMsg();
                JSONObject msgJSON;
                JSONObject body;
                if (!StringUtil.isEmpty(msgObject) && null != (msgJSON = JSONObject.parseObject(msgObject)) && null != (body = msgJSON.getJSONObject("body"))){
                    if((!Objects.equals(body.getString("content"),mq.getContent())|| !Objects.equals(body.getString("title"),mq.getTitle()))){
                        delIdList.add(pushEntity.getId());
                        continue;
                    }
                }
                // 推送人员改了要增加（少了不减少之前已经推送的）
                String pushObject = pushEntity.getPushObject();
                if (!StringUtil.isEmpty(pushObject)) {
                    userIdList = JSON.parseArray(pushObject, String.class);
                }
                mq.getUserIds().removeAll(userIdList);
                if (mq.getUserIds().size()==0){
                    mqIterator.remove();
                }
            }
        }

        if (delIdList.size()>0){
            pushModel.deleteByIdIn(delIdList,corpid);
        }

        // 8.调用消息增加接口
        if (mqDTOArrayList.size()>0){
            count = mqDTOArrayList.size();
            start = 0;
            pageNum = 200;
            for (; start <= count; start = start + pageNum) {
                // 分组数据的endIndex
                int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                List<MessageRabbitMqDTO> subList = mqDTOArrayList.subList(start, endIndex);
                if (subList.size()>0){
                    dataWarningService.dwMessageAdd(new DataWarningMessageAddDTO(){{setCorpid(corpid);setMessageRabbitMqDTOList(subList);}});
                }
            }
        }
        // 9.日志

    }

    private int handleSingleChartEntity(HandleSingleChartDTO handleSingleChartDTO) throws XbbException {
        // 加载数据
        Integer executeCount = handleSingleChartDTO.getExecuteCount();
        Integer executeNumber = handleSingleChartDTO.getExecuteNumber();
        String corpid = handleSingleChartDTO.getCorpid();
        ChartEntity chartEntity = handleSingleChartDTO.getChartEntity();
        Map<Long,List<DataWarningEntity>> chartIdWithDwEntityMap = handleSingleChartDTO.getChartIdWithDwEntityMap();
        long dwTriggerTime = handleSingleChartDTO.getDwTriggerTime();
        Map<Long,List<UserEntity>> executorMap = handleSingleChartDTO.getExecutorMap();
        Map<Long,PaasFormExplainEntity> formIdWithExplainMap = handleSingleChartDTO.getFormIdWithExplainMap();
        Map<Long,String> formIdNameMap = handleSingleChartDTO.getFormIdNameMap();
        Map<Long,WorkOrderExplainEntity> workOrderFormIdWithExplainMap = handleSingleChartDTO.getWorkOrderFormIdWithExplainMap();
        Map<Long,String> workOrderFormIdNameMap = handleSingleChartDTO.getWorkOrderFormIdNameMap();
        Map<Long,Map<String,String>> chartIdWithComputedAttrMap = handleSingleChartDTO.getChartIdWithComputedAttrMap();
        List<DataWarningHistoryEntity> insertHistoryList = handleSingleChartDTO.getInsertHistoryList();
        List<MessageRabbitMqDTO> mqDTOArrayList = handleSingleChartDTO.getMqDTOArrayList();
        Map<Long,List<String>> executorUserIdMap = handleSingleChartDTO.getExecutorUserIdMap();
        List<DataWarningEntity> updateList = handleSingleChartDTO.getUpdateList();
        Integer page = handleSingleChartDTO.getPage();
        Boolean isModifUpdateList = true;
        // 循环次数判断
        if (executeCount >= executeNumber){
            return 0;
        }
        // 调用图表的接口返回图表数据start
        ChartResultDetailVO  chartResultDetailVO = new ChartResultDetailVO();
        ChartResultDetailVO finalChartResultDetailVO = chartResultDetailVO;
        Integer finalPage = page;
        chartResultDetailVO = chartResultService.gitDiyResult(new DiyResultDTO(){{
            setCorpid(corpid);
            setChartEntity(chartEntity);
            ChartResultPojo chartResultPojo = chartDtoHelp.getChartResultPojo4Dw(new ChartResultDTO(){{setCorpid(corpid);}});
            if (Objects.nonNull(finalPage)){
                chartResultPojo.setPage(finalPage);
            }
            chartResultPojo.setIsWarningSync(true);
            chartResultPojo.setSortStatisticsMap(Collections.EMPTY_MAP);
            setChartResultPojo(chartResultPojo);
            setChartResultDetailVO(finalChartResultDetailVO);
            setIsWarningSync(true);
        }});
        // 调用图表的接口返回图表数据end

        // 如果返回接口不为空，这图张表有数据，判断里面的数据是否触发了数据预警
        // 单个图表调用的话，按理说只会返回一个chart的数据
        if (Objects.isNull(chartResultDetailVO)){
            return 0;
        }

        ResultChartVO chartVO;
        ChartTypeEnum chartTypeEnum = ChartTypeEnum.getByCode(chartEntity.getChartType());
        // 柱形图和折线图判断预警需要的数据
        List<String> xAxisKeys = new ArrayList<>();
        List<String> legendKeys = new ArrayList<>();
        List<ResultDataChartVO> data = new ArrayList<>();
        String xAxisKey = "";
        String legendKey = "";
        if (Objects.equals(chartEntity.getChartType(),ChartTypeEnum.BAR_CHART.getCode()) || Objects.equals(chartEntity.getChartType(),ChartTypeEnum.LINE_CHART.getCode())){
            if (CollectionUtils.isEmpty(chartResultDetailVO.getChart())){
                return 0;
            }
            chartVO =  chartResultDetailVO.getChart().get(0);
            // 柱形图和折线图判断预警需要的数据
            xAxisKeys = chartVO.getXAxisKeys();
            legendKeys = chartVO.getLegendKeys();
            data = chartVO.getData();
        }

        // 统计图和指标图需要的数据
        ResultTableVO table = chartResultDetailVO.getTable();
        JSONObject head;

        // 指标图特有的数据
        List<JSONObject> customData;
        List<JSONObject> customTitle;

        // 获取到这个图表的预警列表
        List<DataWarningEntity> dataWarningEntities = chartIdWithDwEntityMap.get(chartEntity.getId());
        Map<Long,Integer> dwIdTriggerNumMap = null != handleSingleChartDTO.getDwIdTriggerNumMap() ? handleSingleChartDTO.getDwIdTriggerNumMap() : new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,String> dwIdConditionStrMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,DataWarningEntity> dwIdEntityMap = dataWarningEntities.stream().collect(Collectors.toMap(DataWarningEntity::getId,dataWarningEntity -> dataWarningEntity));
        long now = DateTimeUtil.getInt();
        switch (chartTypeEnum){
            case DATA_STATISTICS_TABLE:
                // 加载一些数据
                JSONArray body = table.getBody();
                head = table.getHead();
                page = null == page ? 1: page;
                PageHelper pageHelper = table.getPageHelper();
                JSONArray child = head.getJSONArray(StringConstant.CHILD);

                List<List<ChildValuePojo>> allRowValueList = getRowAttrList(null, 0, child,null);
                // 定位所需要的列分组
                List<ChildValuePojo> colValuePojoList;
                // 定位所需要的行分组
                List<ChildValuePojo> rowValuePojoList;

                now = DateTimeUtil.getInt();
                for (int i = 0; i < body.size(); i++) {
                    // 循环次数判断
                    if (executeCount >= executeNumber){
                        break;
                    }
                    // 获取到列分组的定位数据
                    colValuePojoList = getColAttrList(i,body,i);
                    // 只有叶子结点才有真正的数据
                    ChildValuePojo leafValue;
                    if (CollectionUtils.isNotEmpty(colValuePojoList)){
                        Iterator<ChildValuePojo> childValuePojoIterator = colValuePojoList.iterator();
                        while (childValuePojoIterator.hasNext()){
                            ChildValuePojo childValuePojo = childValuePojoIterator.next();
                            leafValue = childValuePojo;
                            if (!leafValue.getIsLeaf()){
                                continue;
                            }
                            JSONArray values = leafValue.getValues();
                            if (Objects.nonNull(values)){
                                // 要移除到最后一个pojo，因为最后一个不是值
//                                    colValuePojoList.remove(colValuePojoList.size()-1);
                                for (int j = 0; j < values.size(); j++) {
                                    // 循环次数判断
                                    if (executeCount >= executeNumber){
                                        break;
                                    }
                                    // 移除掉小计
                                    rowValuePojoList = allRowValueList.get(j);
                                    if (CollectionUtils.isNotEmpty(rowValuePojoList)){
                                        ChildValuePojo valuePojo = rowValuePojoList.get(0);
                                        if(Objects.equals(valuePojo.getValue(),StringConstant.SUB_TOTAL) && "".equals(valuePojo.getKey())){
                                            continue;
                                        }
                                    }
                                    for (DataWarningEntity entity : dataWarningEntities) {
                                        // 判断这个汇总值是不是此数据预警里面的触发条件（多表有可能有相同的attr，根据formId区分）
                                        List<DwTriggerConditionPojo> triggerConditionPojoList = entity.getTriggerCondition().toJavaList(DwTriggerConditionPojo.class);
                                        Long leafFormId = leafValue.getFormId();
                                        if (CollectionUtils.isEmpty(triggerConditionPojoList) && Objects.isNull(leafFormId)){
                                            continue;
                                        }else if(!Objects.equals(leafFormId,triggerConditionPojoList.get(0).getFormId()) || !Objects.equals(leafValue.getKey(),triggerConditionPojoList.get(0).getAttr())){
                                            continue;
                                        }
                                        if (checkIsTrigger(entity.getTriggerCondition(),String.valueOf(values.get(j)))){
                                            // 历史预警的data
                                            DwHistoryDataPojo pojo = new DwHistoryDataPojo();
                                            rowValuePojoList = allRowValueList.get(j);
                                            pojo.setTriggerCondition(JSONArray.parseArray(entity.getTriggerCondition().toJSONString(),DwTriggerConditionPojo.class));
                                            pojo.setColGroupAttrs(colValuePojoList);
                                            pojo.setRowGroupAttrs(rowValuePojoList);
                                            pojo.setWarnValue(new BigDecimal(values.get(j).toString().replaceAll(",","").replaceAll("%","")));
                                            pojo.setTriggerTime(now);
                                            pojo.setDwTriggerTime(dwTriggerTime);
                                            pojo.setWarningName(entity.getName());
                                            // 执行人的查询
                                            pojo.setExecutor(JSONArray.parseArray(JSON.toJSONString(executorMap.get(entity.getId()))));
                                            pojo = packageHisData(entity,pojo,dwIdConditionStrMap,dwIdTriggerNumMap,formIdWithExplainMap,formIdNameMap,workOrderFormIdWithExplainMap,workOrderFormIdNameMap,chartIdWithComputedAttrMap);
                                            insertHistoryList(insertHistoryList,corpid,entity.getId(),chartEntity.getId(),pojo,1,now);
                                            // 循环次数判断
                                            if (++executeCount >= executeNumber){
                                                break;
                                            }

                                        }
                                    }

                                }
                            }
                        }
                    }

                }
                if (Objects.nonNull(pageHelper) && ++page <= pageHelper.getPageTotal()){
                    handleSingleChartDTO.setPage(page);
                    handleSingleChartDTO.setDwIdTriggerNumMap(dwIdTriggerNumMap);
                    handleSingleChartDTO.setExecuteCount(executeCount);
                    // 循环次数判断
                    if (executeCount >= executeNumber){
                        break;
                    }
                    executeCount = handleSingleChartEntity(handleSingleChartDTO);
                    isModifUpdateList = false;
                }else {
                    isModifUpdateList = true;
                }
                break;
            case TARGET_CHART:
                customData = table.getCustomData();
                customTitle = table.getCustomTitle();
                page = null == page ? 1: page;
                pageHelper = table.getPageHelper();
                String key;
                String value;
                if (Objects.nonNull(customTitle) && customTitle.size()>1){
                    key = customTitle.get(0).getString(StringConstant.KEY);
                    value = customTitle.get(1).getString(StringConstant.KEY);
                }else {
                    return 0;
                }
                now = DateTimeUtil.getInt();
                for (JSONObject item : customData) {
                    // 循环次数判断
                    if (executeCount >= executeNumber){
                        break;
                    }
                    ChildValuePojo keyPojo = JSONObject.parseObject(item.getJSONObject(key).toJSONString(), ChildValuePojo.class);
                    ChildValuePojo valuePojo = JSONObject.parseObject(item.getJSONObject(value).toJSONString(), ChildValuePojo.class);
                    // 指标图第一个是定位，第二个是值
                    for (DataWarningEntity entity : dataWarningEntities){
                        if (checkIsTrigger(entity.getTriggerCondition(), String.valueOf(valuePojo.getOriginValue()))) {
                            // 历史预警的data
                            DwHistoryDataPojo pojo = new DwHistoryDataPojo();
                            pojo.setTriggerCondition(JSONArray.parseArray(entity.getTriggerCondition().toJSONString(), DwTriggerConditionPojo.class));
                            pojo.setColGroupAttrs(new ArrayList<ChildValuePojo>() {{add(valuePojo);}});
                            pojo.setRowGroupAttrs(new ArrayList<ChildValuePojo>() {{ add(keyPojo);}});
                            pojo.setWarnValue(new BigDecimal(valuePojo.getOriginValue().replaceAll(",","").replaceAll("%","")));
                            pojo.setTriggerTime(now);
                            pojo.setDwTriggerTime(dwTriggerTime);
                            pojo.setWarningName(entity.getName());
                            // 执行人的查询
                            pojo.setExecutor(JSONArray.parseArray(JSON.toJSONString(executorMap.get(entity.getId()))));
                            pojo = packageHisData(entity,pojo,dwIdConditionStrMap,dwIdTriggerNumMap,formIdWithExplainMap,formIdNameMap,workOrderFormIdWithExplainMap,workOrderFormIdNameMap,chartIdWithComputedAttrMap);
                            // 触发预警，加入到insertHistoryList
                            insertHistoryList(insertHistoryList,corpid,entity.getId(),chartEntity.getId(),pojo,1,now);
                            // 循环次数判断
                            if (++executeCount >= executeNumber){
                                break;
                            }
                        }
                    }
                }
                if (Objects.nonNull(pageHelper) && ++page <= pageHelper.getPageTotal()){
                    handleSingleChartDTO.setPage(page);
                    handleSingleChartDTO.setDwIdTriggerNumMap(dwIdTriggerNumMap);
                    handleSingleChartDTO.setExecuteCount(executeCount);
                    // 循环次数判断
                    if (executeCount >= executeNumber){
                        break;
                    }
                    executeCount = handleSingleChartEntity(handleSingleChartDTO);
                    isModifUpdateList = false;
                }else {
                    isModifUpdateList = true;
                }
                break;
            case BAR_CHART:
            case LINE_CHART:
            case BIAXIAL_CHART:
                now = DateTimeUtil.getInt();
                int chartValueSize = 0;
                int chartValueSecondSize = 0;
                if (CollectionUtils.isNotEmpty(chartEntity.getChartValue())){
                    chartValueSize = chartEntity.getChartValue().size();
                }
                if (CollectionUtils.isNotEmpty(chartEntity.getChartValueSecond())){
                    chartValueSecondSize = chartEntity.getChartValueSecond().size();
                }
                for (int i = 0; i < data.size(); i++) {
                    // 循环次数判断
                    if (executeCount >= executeNumber){
                        break;
                    }

                    String side = (i+1) <= chartValueSize ? PaasConstant.LEFT : PaasConstant.RIGHT;
                    if (legendKeys.size()-1 >= i){
                        legendKey = legendKeys.get(i) + "&" + side;
                    }else {
                        legendKey = "";
                    }
                    JSONArray values = data.get(i).getValue();
                    Long formId = data.get(i).getFormId();
                    String attr = data.get(i).getAttr();
                    String originAttr = data.get(i).getOriginAttr();
                    for (int j = 0; j < values.size() ; j++) {
                        // 循环次数判断
                        if (executeCount >= executeNumber){
                            break;
                        }
                        xAxisKey = xAxisKeys.get(j);
                        for (DataWarningEntity entity : dataWarningEntities) {
                            // 判断这个汇总值是不是此数据预警里面的触发条件（多表有可能有相同的attr，根据formId区分）
                            List<DwTriggerConditionPojo> triggerConditionPojoList = entity.getTriggerCondition().toJavaList(DwTriggerConditionPojo.class);
                            if (CollectionUtils.isEmpty(triggerConditionPojoList)){
                                continue;
                            }else if(!Objects.equals(formId,triggerConditionPojoList.get(0).getFormId()) || !(Objects.equals(attr,triggerConditionPojoList.get(0).getAttr()) || Objects.equals(originAttr,triggerConditionPojoList.get(0).getAttr()) )){
                                continue;
                            }
                            if (checkIsTrigger(entity.getTriggerCondition(),String.valueOf(values.get(j)))){
                                // 历史预警的data
                                DwHistoryDataPojo pojo = new DwHistoryDataPojo();
                                pojo.setTriggerCondition(JSONArray.parseArray(entity.getTriggerCondition().toJSONString(),DwTriggerConditionPojo.class));
                                pojo.setXAxisKey(xAxisKey);
                                pojo.setLegendKey(legendKey);
                                pojo.setWarnValue(new BigDecimal(values.get(j).toString().replaceAll(",","").replaceAll("%","")));
                                pojo.setTriggerTime(now);
                                // 执行人的查询
                                pojo.setExecutor(JSONArray.parseArray(JSON.toJSONString(executorMap.get(entity.getId()))));
                                pojo.setDwTriggerTime(dwTriggerTime);
                                pojo.setWarningName(entity.getName());
                                pojo = packageHisData(entity,pojo,dwIdConditionStrMap,dwIdTriggerNumMap,formIdWithExplainMap,formIdNameMap,workOrderFormIdWithExplainMap,workOrderFormIdNameMap,chartIdWithComputedAttrMap);
                                // 触发预警，加入到insertHistoryList
                                insertHistoryList(insertHistoryList,corpid,entity.getId(),chartEntity.getId(),pojo,1,now);
                                // 循环次数判断
                                if (++executeCount >= executeNumber){
                                    break;
                                }
                            }
                        }

                    }
                }
                break;
            default:
                break;
        }
        long finalNow = now;
        Boolean finalIsModifUpdateList = isModifUpdateList;
        dwIdTriggerNumMap.forEach((k, v) ->{
            // 消息
            DataWarningEntity dataWarningEntity = dwIdEntityMap.get(k);
            mqDTOArrayList.add(getMessage(dataWarningEntity,chartEntity.getId(),corpid,executorUserIdMap.get(k),chartEntity.getCategoryId()));
            if (finalIsModifUpdateList){
                updateList.add(new DataWarningEntity(){{setId(k);setTriggerNum(dataWarningEntity.getTriggerNum()+ v);setLastTriggerTime(finalNow);}});
            }
        });
       return executeCount;
    }

    public static boolean isNumber(String str){
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    /**
     *  通过返回的数据，判断当前这个预警设置是否被触发了。
     * @return
     */
    private boolean checkIsTrigger(JSONArray triggerCondition,String dataValue){
        if (Objects.nonNull(triggerCondition) && null != dataValue && !dataValue.isEmpty()){
            List<DwTriggerConditionPojo> triggerConditionPojos = triggerCondition.toJavaList(DwTriggerConditionPojo.class);
            for (DwTriggerConditionPojo pojo : triggerConditionPojos) {
                String symbol = pojo.getSymbol();
                List<BigDecimal> value = pojo.getValue();
                if (CollectionUtils.isEmpty(value)){
                    return false;
                }
                BigDecimal firstValue = value.get(0);
                DataWarningConditionEnum conditionEnum = DataWarningConditionEnum.getBySymbol(symbol);
                BigDecimal dataNumberValue;
                if (dataValue.charAt(dataValue.length()-1) == '&'){
                    firstValue = firstValue.multiply(new BigDecimal("100"));
                }
                if (isNumber(dataValue = dataValue.replaceAll(",","").replaceAll("%",""))){
                    dataNumberValue = new BigDecimal(dataValue);
                }else {
                    return false;
                }

                switch (conditionEnum) {
                    case GREATEREQUAL:
                        if (dataNumberValue.compareTo(firstValue) >= 0) {
                            return true;
                        }
                        break;
                    case GREATERTHAN:
                        if (dataNumberValue.compareTo(firstValue) > 0) {
                            return true;
                        }
                        break;
                    case LESSEQUAL:
                        if (dataNumberValue.compareTo(firstValue) <= 0) {
                            return true;
                        }
                        break;
                    case LESSTHAN:
                        if (dataNumberValue.compareTo(firstValue) < 0) {
                            return true;
                        }
                        break;
                    case RANGE:
                        if (value.size() < PaasConstant.RANGE_SIZE){
                            return false;
                        }
                        if (dataNumberValue.compareTo(firstValue) >= 0 && dataNumberValue.compareTo(value.get(1)) < 0) {
                            return true;
                        }
                        break;
                    default:
                        return false;
                }

            }
        }
        return false;
    }

    /**
     * 判断单个图表要展示的值在此图表的数据预警设置里面触发条件里面可以找到，如果找不到，则不需要判断是否触发预警
     * @return
     */
    private Boolean includeTriggerCondition(ChartEntity chartEntity, List<DataWarningEntity> list, ChartTypeEnum chartTypeEnum){
        Boolean flag = false;
        Iterator<DataWarningEntity> iterator = list.iterator();
        while (iterator.hasNext()){
            DataWarningEntity entity = iterator.next();
            List<DwTriggerConditionPojo> dwTriggerConditionPojoList = entity.getTriggerCondition().toJavaList(DwTriggerConditionPojo.class);
            // 目前写死只有一个触发条件
            if (CollectionUtils.isNotEmpty(dwTriggerConditionPojoList)) {
                DwTriggerConditionPojo pojo = dwTriggerConditionPojoList.get(0);
                List<FieldAttrPojo> fieldAttrList = new ArrayList<>();
                if (Objects.equals(chartTypeEnum.getCode(), DATA_STATISTICS_TABLE.getCode()) || Objects.equals(chartTypeEnum.getCode(), ChartTypeEnum.TARGET_CHART.getCode())) {
                    fieldAttrList = JSONArray.parseArray(chartEntity.getSummaryAttr().toJSONString(), FieldAttrPojo.class);
                } else if (Objects.equals(chartTypeEnum.getCode(), BAR_CHART.getCode()) || Objects.equals(chartTypeEnum.getCode(), ChartTypeEnum.LINE_CHART.getCode())) {
                    fieldAttrList = JSONArray.parseArray(chartEntity.getChartValue().toJSONString(), FieldAttrPojo.class);
                } else if (Objects.equals(chartEntity.getChartType(),ChartTypeEnum.BIAXIAL_CHART.getCode()))
                {
                    JSONArray chartValue = chartEntity.getChartValue();
                    JSONArray chartValueSecond = chartEntity.getChartValueSecond();
                    if (CollectionUtils.isNotEmpty(chartValue)){
                        fieldAttrList = JSONArray.parseArray(chartValue.toJSONString(),FieldAttrPojo.class);
                    }
                    if (CollectionUtils.isNotEmpty(chartValueSecond)){
                        fieldAttrList.addAll(JSONArray.parseArray(chartValueSecond.toJSONString(),FieldAttrPojo.class));
                    }
                    fieldAttrList = JSONArray.parseArray(chartEntity.getChartValue().toJSONString(),FieldAttrPojo.class);
                }else {
                    return false;
                }
                List<String> attrs = fieldAttrList.stream().map(FieldAttrPojo::getAttr).collect(Collectors.toList());
                if (attrs.contains(pojo.getAttr())) {
                    flag = true;
                }else {
                    iterator.remove();
                }
            }
        }
        return flag;

    }

    /**
     * 过滤图表,（统计图：汇总字段不包含此图表中预警设置的任一一个触发条件则过滤此图表。指标图：指标...。柱形图/折线图：值...。）
     * @param chartEntityList
     * @param chartIdWithDwEntityMap
     */
    private DwFilterChartPojo filterChart(String corpid,List<ChartEntity> chartEntityList, Map<Long,List<DataWarningEntity>> chartIdWithDwEntityMap,Set<Long> countFormIdList,Set<Long> workOrderCountFormIdList) throws XbbException {
        DwFilterChartPojo dwFilterChartPojo = new DwFilterChartPojo();
        List<DataWarningEntity> dataWarningEntityList = new ArrayList<>();
        Iterator<ChartEntity> iterator = chartEntityList.iterator();
        List<Long> formIdList = new ArrayList<>();
        // 工单特殊处理
        List<Long> workOrderFormIdList = new ArrayList<>();
        Map<Long,Map<String,String>> chartIdWithComputedAttrMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        JSONObject driverSourcesObject;
        JSONArray slaveSources;
        while (iterator.hasNext()){
            ChartEntity chartEntity = iterator.next();
            Long chartId = chartEntity.getId();
            List<DataWarningEntity> list = chartIdWithDwEntityMap.get(chartId);
            if (CollectionUtils.isEmpty(list) ){
                iterator.remove();
                chartIdWithDwEntityMap.remove(chartId);
            }
            ChartTypeEnum chartTypeEnum = ChartTypeEnum.getByCode(chartEntity.getChartType());
            switch (chartTypeEnum){
                case DATA_STATISTICS_TABLE:
                case TARGET_CHART:
                    if(!includeTriggerCondition(chartEntity,list,DATA_STATISTICS_TABLE)){
                        iterator.remove();
                        chartIdWithDwEntityMap.remove(chartId);
                        continue;
                    }else {
                        chartIdWithDwEntityMap.put(chartId,list);
                    }
                    break;
                case BAR_CHART:
                case LINE_CHART:
                    if(!includeTriggerCondition(chartEntity,list,BAR_CHART)){
                        iterator.remove();
                        chartIdWithDwEntityMap.remove(chartId);
                        continue;
                    }else {
                        chartIdWithDwEntityMap.put(chartId,list);
                    }
                    break;
                case BIAXIAL_CHART:
                    if(!includeTriggerCondition(chartEntity,list,BIAXIAL_CHART)){
                        iterator.remove();
                        chartIdWithDwEntityMap.remove(chartId);
                        continue;
                    }else {
                        chartIdWithDwEntityMap.put(chartId,list);
                    }
                    break;
                default:
                    break;
            }
            dataWarningEntityList.addAll(list);
            driverSourcesObject = chartEntity.getDriverSources();
            slaveSources=chartEntity.getSlaveSources();
            if (Objects.nonNull(driverSourcesObject)){
                if (Objects.equals(driverSourcesObject.getInteger("businessType"),XbbRefTypeEnum.WORK_ORDER.getCode())){
                    workOrderFormIdList.add(driverSourcesObject.getLong("formId"));
                }else {
                    formIdList.add(driverSourcesObject.getLong("formId"));
                }
            }
            slaveSources.forEach(item->{
                JSONObject slaveSourcesObj = (JSONObject) item;
                if (Objects.equals(slaveSourcesObj.getInteger("businessType"),XbbRefTypeEnum.WORK_ORDER.getCode())){
                    workOrderFormIdList.add(slaveSourcesObj.getLong("formId"));
                }else {
                    formIdList.add(slaveSourcesObj.getLong("formId"));
                }
            });
            // 计算字段查询相对应的名称
            // 单个图表的计算字段，attr对应attrName;
            Map<String,String> computedAttrNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            JSONArray computedAttrJsonArray = chartEntity.getComputedAttr();
            List<FieldAttrPojo> computedAttrList = new ArrayList<>();
            if (Objects.nonNull(computedAttrJsonArray)){
                Set<String> dwAttrSet = new HashSet<>();
                if (CollectionUtils.isNotEmpty(list)){
                    list.forEach(dwItem ->{
                        List<DwTriggerConditionPojo> dwTriggerConditionPojoList = dwItem.getTriggerCondition().toJavaList(DwTriggerConditionPojo.class);
                        if (CollectionUtils.isNotEmpty(dwTriggerConditionPojoList)){
                            DwTriggerConditionPojo pojo = dwTriggerConditionPojoList.get(0);
                            dwAttrSet.add(pojo.getAttr());
                        }
                    });
                }
                computedAttrList = JSON.parseArray(computedAttrJsonArray.toJSONString(),FieldAttrPojo.class);
                computedAttrList.forEach(item ->{
                    if (dwAttrSet.contains(item.getAttr())){
                        computedAttrNameMap.put(item.getAttr(),item.getLabelName());
                    }
                });
            }
            if (computedAttrNameMap.size() > 0){
                chartIdWithComputedAttrMap.put(chartEntity.getId(),computedAttrNameMap);
            }
        }

        // 根据formId集合查询相关解释
        HashMap<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PaasFormExplainEntity> explainEntityList;
        List<WorkOrderExplainEntity> workOrderEntityList;
        Map<Long,PaasFormExplainEntity> formIdWithExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,WorkOrderExplainEntity> workOrderFormIdWithExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PaasFormEntityExt> formEntityExtList;
        List<WorkOrderFormEntity> workOrderFormEntityList;
        Map<Long,String> formIdNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,String> workOrderFormIdNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionUtils.isNotEmpty(formIdList)) {
            Set<Long> temp = new HashSet<>(formIdList);
            param.clear();
            param.put("formIdIn", temp);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL,0);
            explainEntityList = paasFormExplainModel.list(param);
            formIdWithExplainMap = explainEntityList.stream().collect(Collectors.toMap(PaasFormExplainEntity::getFormId, explainEntity -> explainEntity));
        }
        if (CollectionUtils.isNotEmpty(workOrderFormIdList)) {
            Set<Long> temp = new HashSet<>(workOrderFormIdList);
            param.clear();
            param.put("formIdIn", temp);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL,0);
            workOrderEntityList = workOrderExplainModel.list(param);
            workOrderFormIdWithExplainMap = workOrderEntityList.stream().collect(Collectors.toMap(WorkOrderExplainEntity::getFormId, explainEntity -> explainEntity));
        }

        // 根据countFormId查询相关form
        if (CollectionUtils.isNotEmpty(countFormIdList)) {
            Set<Long> temp = new HashSet<>(formIdList);
            param.clear();
            param.put("idIn", temp);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL,0);
            formEntityExtList = paasFormModel.list(param);
            formIdNameMap = formEntityExtList.stream().collect(Collectors.toMap(PaasFormEntityExt::getId, PaasFormEntityExt::getName));
        }
        if (CollectionUtils.isNotEmpty(workOrderCountFormIdList)) {
            Set<Long> temp = new HashSet<>(workOrderFormIdList);
            param.clear();
            param.put("idIn", temp);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL,0);
            workOrderFormEntityList = workOrderFormModel.findEntitys(param);
            workOrderFormIdNameMap = workOrderFormEntityList.stream().collect(Collectors.toMap(WorkOrderFormEntity::getId, WorkOrderFormEntity::getName));
        }
        dwFilterChartPojo.setDataWarningEntityList(dataWarningEntityList);
        dwFilterChartPojo.setFormIdNameMap(formIdNameMap);
        dwFilterChartPojo.setFormIdWithExplainMap(formIdWithExplainMap);
        dwFilterChartPojo.setWorkOrderFormIdWithExplainMap(workOrderFormIdWithExplainMap);
        dwFilterChartPojo.setWorkOrderFormIdNameMap(workOrderFormIdNameMap);
        dwFilterChartPojo.setChartIdWithComputedAttrMap(chartIdWithComputedAttrMap);
        return dwFilterChartPojo;
    }

    /**
     * 从图表里面返回的数据提取出行分组
     * @param pojos
     * @param startIndex
     * @param child
     * @param list
     */
    private List<List<ChildValuePojo>> getRowAttrList(List<List<ChildValuePojo>> pojos , int startIndex, JSONArray child,List<ChildValuePojo> list){
        List<List<ChildValuePojo>> resultPojos = (null != pojos ) ? pojos : new ArrayList<>();
        for (int i = startIndex ; i < child.size() ; i++) {
            JSONObject subChild = child.getJSONObject(i);
            if (subChild.getBoolean(StringConstant.HEAD)){
                continue;
            }
            List<ChildValuePojo> resultList = (null != list ) ? list : new ArrayList<>();
            resultList.add(new ChildValuePojo(subChild.getString(StringConstant.KEY),subChild.getString(StringConstant.ORIGIN_VALUE),subChild.getString(StringConstant.VALUE),subChild.getLongValue(StringConstant.FORM_ID)));
            if (Objects.nonNull(subChild.getJSONArray(StringConstant.CHILD))&&subChild.getJSONArray(StringConstant.CHILD).size()>0){
                for (int j = 0; j < subChild.getJSONArray(StringConstant.CHILD).size() ; j++) {
                    JSONObject sSubChild = subChild.getJSONArray(StringConstant.CHILD).getJSONObject(j);
                    List<ChildValuePojo> tempResultList = new ArrayList<>(resultList);
                    tempResultList.add(new ChildValuePojo(sSubChild.getString(StringConstant.KEY),sSubChild.getString(StringConstant.ORIGIN_VALUE),sSubChild.getString(StringConstant.VALUE),subChild.getLongValue(StringConstant.FORM_ID)));
                    if (Objects.nonNull(sSubChild.getJSONArray(StringConstant.CHILD))&&sSubChild.getJSONArray(StringConstant.CHILD).size()>0){
                        List<List<ChildValuePojo>> tempResults = getRowAttrList(pojos,0,sSubChild.getJSONArray(StringConstant.CHILD),tempResultList);
                        resultPojos.addAll(tempResults);
                    }else {
                        resultPojos.add(new ArrayList<ChildValuePojo>(){{addAll(resultList);}});
                    }
                }
            }else {
                resultPojos.add(new ArrayList<ChildValuePojo>(){{addAll(resultList);}});
            }
        }
        return resultPojos;
    }

    /**
     * 从图表里面返回的数据提取出列分组
     * @param startIndex
     * @param child
     * @param endIndex
     */
    private List<ChildValuePojo> getColAttrList(int startIndex,JSONArray child,int endIndex){
        List<ChildValuePojo> pojos = new ArrayList<>();
        for (int i = startIndex ; i <= endIndex ; i++) {
            JSONObject subChild = child.getJSONObject(i);
            if (subChild.getBooleanValue(StringConstant.IS_LEAF)){
                pojos.add(new ChildValuePojo(subChild.getString(StringConstant.KEY),subChild.getString(StringConstant.ORIGIN_VALUE),subChild.getJSONArray(StringConstant.VALUES),subChild.getBooleanValue(StringConstant.IS_LEAF),subChild.getLongValue(StringConstant.FORM_ID)));
            }else {
                pojos.add(new ChildValuePojo(subChild.getString(StringConstant.KEY),subChild.getString(StringConstant.ORIGIN_VALUE),subChild.getString(StringConstant.VALUE),subChild.getLongValue(StringConstant.FORM_ID)));
            }
            if (Objects.nonNull(subChild.getJSONArray(StringConstant.CHILD))&&subChild.getJSONArray(StringConstant.CHILD).size()>0){
                pojos.addAll(getColAttrList(0,subChild.getJSONArray(StringConstant.CHILD),subChild.getJSONArray(StringConstant.CHILD).size()-1));
            }
        }
        return pojos;
    }

    /**
     * 触发预警，加入到insertHistroyList
     * @param insertHistroyList
     * @param corpid
     * @param dataWarningId
     * @param chartId
     * @param dataPojo
     * @param triggerNum
     * @param now
     */
    private void insertHistoryList(List<DataWarningHistoryEntity> insertHistroyList,String corpid,Long dataWarningId, Long chartId, DwHistoryDataPojo dataPojo,int triggerNum,long now){
        insertHistroyList.add(new DataWarningHistoryEntity(corpid,dataWarningId, chartId, JSONObject.parseObject(JSON.toJSONString(dataPojo)),
                JSONArray.parseArray(JSON.toJSONString(new ArrayList<Integer>() {{add(ActionTypeEnum.MESSAGE.getCode());}})), 0,
                triggerNum, now, now, 0));
    }

    /**
     * package消息
     * @param entity
     * @param chartId
     * @param corpid
     * @param userIds
     * @return
     */
    public MessageRabbitMqDTO getMessage(DataWarningEntity entity,Long chartId,String corpid,List<String> userIds,Long categoryId){
        // TODO 消息
        String title = entity.getName();
        String content = entity.getMemo();
        JSONObject strategy = entity.getStrategy();
        String strategyTime = strategy.getString("strategyTime");
        strategyTime = strategyTime.substring(0, strategyTime.indexOf(":"));
        int stIntValue = Integer.parseInt(strategyTime);
        Integer strategyType = strategy.getInteger("strategyType");
        DataWarningStrategyTypeEnum strategyTypeEnum = DataWarningStrategyTypeEnum.getByCode(strategyType);
        // 当前时间的小时
        int curHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        Calendar calendar = Calendar.getInstance();
        switch (strategyTypeEnum){
            case DAILY:
                if (stIntValue <= curHour){
                    // 取第二天
                    calendar = Calendar.getInstance();
                    calendar.add(Calendar.DATE, 1);
                    calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                }else {
                    // 取当天
                    calendar = Calendar.getInstance();
                    calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                }
                break;
            case WEEKLY:
                // 获取今天是星期几
                int strategyWeek = strategy.getInteger("strategyWeek");
                calendar = Calendar.getInstance();
                int week = calendar.get(Calendar.DAY_OF_WEEK);
                if (strategyWeek >= week ){
                    if (strategyWeek == week && stIntValue <= curHour){
                        // 取第二周
                        calendar.setTime(new Date());
                        calendar.add(Calendar.DAY_OF_WEEK,1);
                        calendar.set(Calendar.DAY_OF_WEEK,week);
                        calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                    }else {
                        // 取当前周
                        calendar.setTime(new Date());
                        calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                    }
                }else {
                    // 取第二周
                    calendar.setTime(new Date());
                    calendar.add(Calendar.DAY_OF_WEEK,1);
                    calendar.set(Calendar.DAY_OF_WEEK,week);
                    calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);

                }
                break;
            case MONTHLY:
                // 获取今天这个月的几号
                int strategyDay = strategy.getInteger("strategyDay");
                calendar = Calendar.getInstance();
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                int maxDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                int maxDayOfNextMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                int curStrategyDay = strategyDay > maxDayOfMonth?maxDayOfMonth:strategyDay;
                int nextStrategyDay = strategyDay > maxDayOfNextMonth?maxDayOfNextMonth:strategyDay;
                if (curStrategyDay >= day){
                    if (curStrategyDay == day && stIntValue <= curHour){
                        // 取下个月
                        calendar.setTime(new Date());
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        calendar.set(Calendar.DAY_OF_MONTH,nextStrategyDay);
                        calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                    }else {
                        // 当前月
                        calendar.setTime(new Date());
                        calendar.set(Calendar.DAY_OF_MONTH,curStrategyDay);
                        calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                    }
                }else {
                    // 下个月
                    calendar.setTime(new Date());
                    calendar.add(Calendar.DAY_OF_MONTH,1);
                    calendar.set(Calendar.DAY_OF_MONTH,nextStrategyDay);
                    calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                }
                break;
            case ANNUALLY:
                String[] strategyDayArray = strategy.getString("strategyDay").split("-");
                int strategyMonth = Integer.parseInt(strategyDayArray[0]);
                strategyDay = Integer.parseInt(strategyDayArray[1]);
                calendar = Calendar.getInstance();
                int month = calendar.get(Calendar.MONTH);
                day = calendar.get(Calendar.DAY_OF_MONTH);
                maxDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                curStrategyDay = strategyDay > maxDayOfMonth?maxDayOfMonth:strategyDay;
                if (strategyMonth >= month ){
                    if (strategyMonth == month && curStrategyDay >= day){
                        if (curStrategyDay == day && stIntValue <= curHour){
                            // 取明年
                            calendar.setTime(new Date());
                            calendar.add(Calendar.YEAR,1);
                            calendar.set(Calendar.MONTH,strategyMonth);
                            calendar.set(Calendar.DAY_OF_MONTH,curStrategyDay);
                            calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                            calendar.set(Calendar.MINUTE, 0);
                            calendar.set(Calendar.SECOND, 0);
                        }else {
                            // 今年
                            calendar.setTime(new Date());
                            calendar.set(Calendar.MONTH,strategyMonth);
                            calendar.set(Calendar.DAY_OF_MONTH,curStrategyDay);
                            calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                            calendar.set(Calendar.MINUTE, 0);
                            calendar.set(Calendar.SECOND, 0);
                        }
                    }else {
                        // 明年
                        calendar.setTime(new Date());
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        calendar.set(Calendar.MONTH,strategyMonth);
                        calendar.set(Calendar.DAY_OF_MONTH,curStrategyDay);
                        calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                    }
                }else {
                    // 取明年
                    calendar.setTime(new Date());
                    calendar.add(Calendar.YEAR,1);
                    calendar.set(Calendar.MONTH,strategyMonth);
                    calendar.set(Calendar.DAY_OF_MONTH,curStrategyDay);
                    calendar.set(Calendar.HOUR_OF_DAY, stIntValue);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                }
                break;
            default:
                break;

        }
        PushRefTypePojo.Options options = new PushRefTypePojo.Options(){{setCategoryId(categoryId);setChartId(chartId);setDataWarningId(entity.getId());}};
        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, userIds, new ArrayList<Long>(){{add(entity.getId());}}, 0,
                calendar.getTimeInMillis()/1000, title, content, null, options);
        return messageRabbitMqDTO;
    }

    /**
     * 加载触发条件str
     * @return
     */
    String getConditionStr(DataWarningEntity entity,Map<Long,PaasFormExplainEntity> formIdWithExplainsMap,Map<Long,String> formIdNameMap, Map<Long,WorkOrderExplainEntity> workOrderFormIdWithExplainMap, Map<Long,String> workOrderFormIdNameMap,Map<Long,Map<String,String>> chartIdWithComputedAttrMap){
        List<DwTriggerConditionPojo> pojoList = JSONArray.parseArray(entity.getTriggerCondition().toJSONString(),DwTriggerConditionPojo.class);
        // 加载触发条件的str
        String triggerConditionStr = "";
        if (CollectionUtils.isNotEmpty(pojoList)) {
            DwTriggerConditionPojo conditionPojo = pojoList.get(0);
            PaasFormExplainEntity paasFormExplainEntity = null;
            WorkOrderExplainEntity workOrderExplainEntity = null;
            if (Objects.equals(conditionPojo.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())){
                workOrderExplainEntity = workOrderFormIdWithExplainMap.get(conditionPojo.getFormId());
            }else if (Objects.nonNull(conditionPojo.getAttr()) &&  conditionPojo.getAttr().contains(StringConstant.COMPUTED_FIELD)){
                Map<String,String> computedAttrMap = chartIdWithComputedAttrMap.get(entity.getChartId());
                if (Objects.nonNull(computedAttrMap)){
                    for (Map.Entry<String, String> entry : computedAttrMap.entrySet()) {
                        String k = entry.getKey();
                        String v = entry.getValue();
                        if (Objects.equals(conditionPojo.getAttr(), k)) {
                            triggerConditionStr = v;
                            break;
                        }
                    }
                }
            }else {
                paasFormExplainEntity = formIdWithExplainsMap.get(conditionPojo.getFormId());
            }
            if (Objects.isNull(paasFormExplainEntity) && Objects.isNull(workOrderExplainEntity) && StringUtil.isEmpty(triggerConditionStr)){
                return triggerConditionStr;
            }
            String attrName = conditionPojo.getAttrName();
            attrName = StringUtil.isNotEmpty(triggerConditionStr) ? triggerConditionStr : attrName;
            if (Objects.nonNull(paasFormExplainEntity)) {
                if (Objects.equals(conditionPojo.getAttr(),PaasConstant.COUNT)){
                    if (null != formIdNameMap.get(conditionPojo.getFormId())){
                        attrName = formIdNameMap.get(conditionPojo.getFormId()) + "-" + "计数";
                    }
                }else {
                    List<FieldAttrEntity> fieldAttrList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                    for (FieldAttrEntity fieldAttrEntity : fieldAttrList) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), conditionPojo.getAttr())) {
                            attrName = fieldAttrEntity.getAttrName();
                            break;
                        }
                    }
                }
            }else if(Objects.nonNull(workOrderExplainEntity)){
                if (Objects.equals(conditionPojo.getAttr(),PaasConstant.COUNT)){
                    if (null != workOrderFormIdNameMap.get(conditionPojo.getFormId())){
                        attrName = workOrderFormIdNameMap.get(conditionPojo.getFormId()) + "-" + "计数";
                    }
                }else {
                    List<FieldAttrEntity> fieldAttrList = JSON.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
                    for (FieldAttrEntity fieldAttrEntity : fieldAttrList) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), conditionPojo.getAttr())) {
                            attrName = fieldAttrEntity.getAttrName();
                            break;
                        }
                    }
                }
            }
            String symbol = conditionPojo.getSymbol();
            List<BigDecimal> value = conditionPojo.getValue();
            if (CollectionUtils.isNotEmpty(value)){
                DataWarningConditionEnum conditionEnum = DataWarningConditionEnum.getBySymbol(symbol);
                switch (conditionEnum) {
                    case GREATEREQUAL:
                    case GREATERTHAN:
                    case LESSEQUAL:
                    case LESSTHAN:
                        triggerConditionStr = attrName + conditionEnum.getMemo() + value.get(0);
                        break;
                    case RANGE:
                        if (value.size() == PaasConstant.RANGE_SIZE){
                            triggerConditionStr = attrName + DataWarningConditionEnum.GREATEREQUAL.getMemo() + value.get(0) + "," + DataWarningConditionEnum.LESSTHAN.getMemo() + value.get(1);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        return triggerConditionStr;
    }

    /**
     * package 历史预警data
     */
    DwHistoryDataPojo packageHisData(DataWarningEntity entity, DwHistoryDataPojo pojo, Map<Long, String> dwIdConditionStrMap, Map<Long, Integer> dwIdTriggerNumMap, Map<Long,PaasFormExplainEntity> formIdWithExplainMap, Map<Long,String> formIdNameMap, Map<Long,WorkOrderExplainEntity> workOrderFormIdWithExplainMap, Map<Long,String> workOrderFormIdNameMap,Map<Long,Map<String,String>> chartIdWithComputedAttrMap){
        // 触发条件拼接成的str
        String triggerConditionStr = dwIdConditionStrMap.get(entity.getId());
        if (null != triggerConditionStr){
            pojo.setTriggerConditionStr(triggerConditionStr);
        }else {
            String conditionStr = getConditionStr(entity,formIdWithExplainMap,formIdNameMap,workOrderFormIdWithExplainMap,workOrderFormIdNameMap,chartIdWithComputedAttrMap);
            pojo.setTriggerConditionStr(conditionStr);
            dwIdConditionStrMap.put(entity.getId(),conditionStr);
        }
        // 此预警的触发次数
        Integer triggerNum =  dwIdTriggerNumMap.get(entity.getId());
        if (null != triggerNum){
            dwIdTriggerNumMap.put(entity.getId(),++triggerNum);
        }else {
            dwIdTriggerNumMap.put(entity.getId(),1);
        }
        return pojo;
    }

}
